layui.define(["form", "layer", "admin", "table", "upload", "element"], function (exports) {
    var $ = layui.$,
        form = layui.form,
        layer = layui.layer,
        admin = layui.admin,
        table = layui.table,
        upload = layui.upload;

    var router = layui.router();

    // 请求基本信息
    admin.req({
        url: "/com/listAllCom",
        beforeSend: function () {
            layer.load(2, {time: 100 * 1000});
        },
        complete: function () {
            layer.closeAll('loading');
        },
        done: function (res) {
            var storeList = res.data.storeList;
            var channelList = res.data.channelList;
            var provinceList = res.data.provinceList;

            var storeSelectObj = $("#bill-express-edit-form select[name=storeCode]");
            $.each(storeList, function (index, value) {
                storeSelectObj.append("<option value='" + value.code + "'>" + value.name + "</option>");
            });

            var channelSelectObj = $("#bill-express-edit-form select[name=channelCode]");
            $.each(channelList, function (index, value) {
                channelSelectObj.append("<option value='" + value.code + "'>" + value.name + "</option>");
            });

            var provinceSelectObj = $("#bill-express-edit-form select[name=receiverProvinceCode]");
            $.each(provinceList, function (index, value) {
                provinceSelectObj.append("<option value='" + value.code + "'>" + value.name + "</option>");
            });

            form.render();

            getBilExpressDetail(); // 请求当前运单详细信息
        }
    });

    upload.render({
        elem: '#id-card-front', //绑定元素
        url: '/bill/uploadIdCardFront', //上传接口
        field: "idCardFront$",
        accept: "images",
        exts: "png|jpg|gif|jpeg|bmp",
        data: {"access_token": layui.data('layuiAdmin').access_token},
        done: function(res){
            //上传完毕回调
            if(res.code === 0) {// 上传成功
                $("#bill-express-edit").trigger("uploadIdCardFront", res.data);
            } else{// 上传失败
                layer.msg("上传失败", {icon: 5, time: 1500});
            }
        },
        error: function(){
            layer.msg("请求异常", {icon: 5, time: 1500});
        }
    });

    upload.render({
        elem: '#id-card-back', //绑定元素
        url: '/bill/uploadIdCardBack', //上传接口
        field: "idCardBack$",
        accept: "images",
        exts: "png|jpg|gif|jpeg|bmp",
        data: {"access_token": layui.data('layuiAdmin').access_token},
        done: function(res){
            //上传完毕回调
            if(res.code === 0) {// 上传成功
                $("#bill-express-edit").trigger("uploadIdCardBack", res.data);
            } else{// 上传失败
                layer.msg("上传失败", {icon: 5, time: 1500});
            }
        },
        error: function(){
            layer.msg("请求异常", {icon: 5, time: 1500});
        }
    });

    table.render({
        elem: '#bill-express-edit-goods-table',
        cols: [[ //表头
            {field: 'barcode', title: '条形码', edit: "text"},
            {field: 'brand', title: '<span style="color: red;">*</span>品牌 例：冠生园', edit: "text"},
            {field: 'name', title: '<span style="color: red;">*</span>品名 例：蜂蜜', edit: "text"},
            {field: 'specs', title: '<span style="color: red;">*</span>规格 例：200粒', edit: "text"},
            {field: 'count', title: '<span style="color: red;">*</span>数量', edit: "text"},
            {field: 'price', title: '<span style="color: red;">*</span>单价(加币)', edit: "text"},
            {field: 'isFirst', title: '是否第一条', hide: "true"},
            {title: '操作', width: 80, templet: '#bill-express-edit-goods-table-tpl'}
        ]],
        data: [],
        even: true
    });

    table.on("tool(bill-express-edit-goods-table)", function(obj) {
        // var data = table.cache["bill-express-edit-goods-table"];
        var data = [];
        var rows = $("#bill-express-edit-form tbody").find("tr");
        $.each(rows, function(index, item) {
            var barcode = $(item).find("td[data-field=barcode]").text();
            var brand = $(item).find("td[data-field=brand]").text();
            var name = $(item).find("td[data-field=name]").text();
            var specs = $(item).find("td[data-field=specs]").text();
            var count = $(item).find("td[data-field=count]").text();
            var price = $(item).find("td[data-field=price]").text();
            var isFirst = "1";
            if(index == "0") {
                isFirst = "0";
            }
            var temp = {"barcode": barcode, "brand": brand, "name": name, "specs": specs, "count": count, "price": price, "isFirst": isFirst};
            data.push(temp);
        });
        if(obj.event === "addGoods") {
            var addedGoods = {"barcode": "", "brand": "", "name": "", "specs": "", "count": "", "price": "", "isFirst": "1"}
            data.push(addedGoods);
        } else if(obj.event === "delGoods"){
            data.pop();
        }
        table.reload("bill-express-edit-goods-table", {
            data: data
        });
    });

    $("#bill-express-edit-choose-sender-btn").off("click").on("click", function() {
        layer.open({
            type: 2,
            area: ['1200px', '600px'],
            title: "发件人列表",
            content: layui.setter.base + 'views/bill/senderList.html'
        });
    });

    $("#bill-express-edit-form select[name=receiverProvinceCode]").change(function() {
        var province = $(this).val();
        var city = $(this).attr("data-city");
        $(this).removeAttr("data-city");

        if(province.length !== 0) {
            var citySelectObj = $("#bill-express-edit-form select[name=receiverCityCode]");
            if ($.inArray(province, ["110000", "120000", "310000", "500000", "810000", "820000"]) !== -1) {
                citySelectObj.parent().hide();
                form.render();
                return;
            }

            var data = {"parentCode": province};
            admin.req({
                url: "/com/listComArea",
                data: data,
                beforeSend: function () {
                    layer.load(2, {time: 100 * 1000});
                },
                complete: function () {
                    layer.closeAll('loading');
                },
                done: function (res) {
                    var data = res.data;

                    citySelectObj.empty();
                    $.each(data, function(index, value) {
                        citySelectObj.append("<option value='"+value.code+"'>"+value.name+"</option>");
                    });

                    citySelectObj.val(city);
                    citySelectObj.parent().show();

                    form.render();
                }
            });
        }
    });

    form.on("submit(bill-express-edit-submit)", function(data) {
        var isBilGoodsOK = true;
        // var bilGoodsList = table.cache["bill-express-edit-goods-table"];
        var bilGoodsList = [];
        var rows = $("#bill-express-edit-form tbody").find("tr");
        $.each(rows, function(index, item) {
            var barcode = $(item).find("td[data-field=barcode]").text();
            var brand = $(item).find("td[data-field=brand]").text();
            var name = $(item).find("td[data-field=name]").text();
            var specs = $(item).find("td[data-field=specs]").text();
            var count = $(item).find("td[data-field=count]").text();
            var price = $(item).find("td[data-field=price]").text();
            var isFirst = "1";
            if(index == "0") {
                isFirst = "0";
            }
            var temp = {"barcode": barcode, "brand": brand, "name": name, "specs": specs, "count": count, "price": price, "isFirst": isFirst};
            console.log(temp);
            bilGoodsList.push(temp);
        });

        $.each(bilGoodsList, function(index, value) {
            var brand = value.brand.trim(), name = value.name.trim(),
                specs = value.specs.trim(), count = value.count.toString().trim(),
                price = value.price.toString().trim();
            if(brand.length === 0 || name.length === 0
                || specs.length === 0 || count.length === 0
                || price.length === 0) {
                layer.msg("物品信息不完整", {icon: 5, time: 1500});
                isBilGoodsOK = false;
            }
        });
        if(!isBilGoodsOK) return false;

        data.field.bilGoods = JSON.stringify(bilGoodsList);
        data.field.id = router.search.id;
        data.field.province = data.field.receiverProvinceCode;
        data.field.city = data.field.receiverCityCode;
        data.field.postcode = data.field.receiverPostcode;

        admin.req({
            url: "/bill/updateBilExpress",
            data: data.field,
            type: "post",
            beforeSend: function () {
                layer.load(2, {time: 100 * 1000});
            },
            complete: function () {
                layer.closeAll('loading');
            },
            done: function (res) {
                layer.msg("编辑成功", {icon: 6, time: 1500}, function () {
                    location.hash = "/bill/expressList";
                });
            }
        });

        return false;
    });

    $("#bill-express-edit").off("uploadIdCardFront").on("uploadIdCardFront", function(e, data) {
        $("#idcard-front-img").show();
        $("#idcard-front-img img").attr('src', '/bill/previewIdCardFront?idCardFront=' + data + "&access_token=" + layui.data('layuiAdmin').access_token);
        $("#idcard-front-img input[name=idCardFront]").val(data);
        var idCardFrontImg = $("#idcard-front-img p");
        idCardFrontImg.html('<a class="layui-btn layui-btn-xs demo-preview">预览</a><a class="layui-btn layui-btn-xs demo-delete">删除</a>');
        idCardFrontImg.find('.demo-delete').off("click").on('click', function(){
            $("#idcard-front-img input[name=idCardFront]").val("");
            admin.req({
                url: "/bill/deleteIdCardFront",
                data: {"idCardFront": data},
                beforeSend: function () {
                    layer.load(2, {time: 100 * 1000});
                },
                complete: function () {
                    layer.closeAll('loading');
                },
                done: function () {
                    $("#idcard-front-img img").removeAttr('src');
                    idCardFrontImg.empty();
                    $("#idcard-front-img").hide();
                }
            });
        });
        idCardFrontImg.find('.demo-preview').off("click").on('click', function(){
            layer.open({
                type: 2,
                shade: 0.3,
                title: false,
                area: ['400px', '300px'],
                content: '/bill/previewIdCardFront?idCardFront=' + data + '&access_token=' + layui.data('layuiAdmin').access_token
            });
        });
    });

    $("#bill-express-edit").off("uploadIdCardBack").on("uploadIdCardBack", function(e, data) {
        $("#idcard-back-img").show();
        $("#idcard-back-img img").attr('src', '/bill/previewIdCardBack?idCardBack=' + data + "&access_token=" + layui.data('layuiAdmin').access_token);
        $("#idcard-back-img input[name=idCardBack]").val(data);
        var idCardBackImg = $("#idcard-back-img p");
        idCardBackImg.html('<a class="layui-btn layui-btn-xs demo-preview">预览</a><a class="layui-btn layui-btn-xs demo-delete">删除</a>');
        idCardBackImg.find('.demo-delete').off("click").on('click', function(){
            $("#idcard-back-img input[name=idCardBack]").val("");
            admin.req({
                url: "/bill/deleteIdCardBack",
                data: {"idCardBack": data},
                beforeSend: function () {
                    layer.load(2, {time: 100 * 1000});
                },
                complete: function () {
                    layer.closeAll('loading');
                },
                done: function () {
                    $("#idcard-back-img img").removeAttr('src');
                    idCardBackImg.empty();
                    $("#idcard-back-img").hide();
                }
            });
        });
        idCardBackImg.find('.demo-preview').off("click").on('click', function(){
            layer.open({
                type: 2,
                shade: 0.3,
                title: false,
                area: ['400px', '300px'],
                content: '/bill/previewIdCardBack?idCardBack=' + data + '&access_token=' + layui.data('layuiAdmin').access_token
            });
        });
    });

    function getBilExpressDetail() {
        admin.req({
            url: "/bill/getBilExpress",
            data: {"id": router.search.id},
            beforeSend: function () {
                layer.load(2, {time: 100 * 1000});
            },
            complete: function () {
                layer.closeAll('loading');
            },
            done: function (res) {
                form.val("bill-express-edit-form", res.data);
                form.render();

                if(res.data.idCardFront && res.data.idCardFront.length !== 0) {
                    $("#bill-express-edit").trigger("uploadIdCardFront", res.data.idCardFront);
                }

                if(res.data.idCardBack && res.data.idCardBack.length !== 0) {
                    $("#bill-express-edit").trigger("uploadIdCardBack", res.data.idCardBack);
                }

                $("#bill-express-edit-form select[name=receiverProvinceCode]").attr("data-city", res.data.receiverCityCode);
                $("#bill-express-edit-form select[name=receiverProvinceCode]").trigger("change");
                listBilGoods(res.data.waybillNo);
            }
        });
    }

    function listBilGoods(waybillNo) {
        admin.req({
            url: "/bill/listBilGoods",
            data: {"waybillNo": waybillNo},
            beforeSend: function () {
                layer.load(2, {time: 100 * 1000});
            },
            complete: function () {
                layer.closeAll('loading');
            },
            done: function (res) {
                var data = table.cache["bill-express-edit-goods-table"];

                console.log(data);

                $.each(res.data, function(index, item) {
                    if(index === 0) {
                        item.isFirst= "0";
                        data.push(item);
                    } else{
                        item.isFirst= "1";
                        data.push(item);
                    }
                });

                table.reload("bill-express-edit-goods-table", {
                    data: data
                });
            }
        });
    }

    exports("expressEdi", {});
});